package com.jydw.da.frame.config.table;

import com.jydw.da.frame.utils.DateUtils;
import com.jydw.da.frame.utils.ShardingAlgorithmTool;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.springframework.stereotype.Component;

import java.util.*;


//sharding分表规则
//按单月分表
public class DateShardingAlgorithm implements StandardShardingAlgorithm<Date> {
    @Getter
    @Setter
    public Properties props = new Properties();

    // 查询使用
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {
        for (String s : collection) {
            System.out.println("节点配置表名为: " + s);
        }
        // 查询数据库中的表 user
        List<String> tableNames = ShardingAlgorithmTool.getAllTableNameBySchema();
        for (String s : tableNames) {
            System.out.println("数据库实时表名: " + s);
        }
        HashSet<String> tableNameCache = ShardingAlgorithmTool.cacheTableNames();
        for (String s : tableNameCache) {
            System.out.println("缓存中的表名: " + s);
        }
        // 返回数据库实时存在的表 如果返回collection会提示表不存在
        return tableNameCache;
    }

    // 添加使用
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        StringBuilder resultTableName = new StringBuilder();
        String logicTableName = preciseShardingValue.getLogicTableName();
        //表前缀
        String prefix = preciseShardingValue.getDataNodeInfo().getPrefix();
        //表名精确匹配，表名加上截取的时间
        resultTableName.append(prefix)
                //时间戳秒级转毫秒级转成date类型
                .append(DateUtils.parseDateToStr(DateUtils.YEAR_MONTH_NUMBER, preciseShardingValue.getValue()));
        System.out.println("插入表名为:" + resultTableName);
        return ShardingAlgorithmTool.shardingTablesCheckAndCreatAndReturn(logicTableName, resultTableName.toString());
    }

    @Override
    public void init(Properties props) {
        this.props = props;
    }

    @Override
    public String getType() {
        //　自定义 这里需要spi支持
        return "DATE_AUTO";
    }
}
